package com.jml.zlhq.app.ui;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jml.zlhq.app.R;
import com.jml.zlhq.app.URLs;
import com.jml.zlhq.app.service.HttpService;
import com.jml.zlhq.app.util.BaseTools;
import com.jml.zlhq.app.util.StringUtil;
import com.jml.zlhq.app.util.UIUtil;
import com.jml.zlhq.app.widgets.NoScrollGridView;
import com.jml.zlhq.app.widgets.RoundImageView;
import com.loopj.android.http.TextHttpResponseHandler;
import com.nostra13.universalimageloader.core.ImageLoader;

public class CityActivity extends BaseActivity implements OnPageChangeListener{
//	private PullToRefreshListView mPullToRefreshView;
//	private ListView listView;
//	private BaseAdapter adapter;
//	private List<JSONObject> listItems = new ArrayList<JSONObject>();
	
	private int currentPageCount=9,count,pageCount=1;
	private List<ImageView> tips = new ArrayList<ImageView>();
	private ViewPager viewPager;
	private PagerAdapter pageAdapter;
	private List<GridView> gridViews = new ArrayList<GridView>();
	private List<JSONObject> citys = new ArrayList<JSONObject>();
	private LinearLayout tipViewGroup;
	private RelativeLayout city_inv_re;
	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				pageAdapter.notifyDataSetChanged();
				break;
			default:
				break;
			}
		}
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.city_activity);
		
		LinearLayout leftLay = (LinearLayout) findViewById(R.id.content_header_left_lay);
		LinearLayout rightLay = (LinearLayout) findViewById(R.id.content_header_right_lay);
		leftLay.setOnClickListener(this);
		rightLay.setOnClickListener(this);
		AutoCompleteTextView centerEdit = (AutoCompleteTextView) findViewById(R.id.content_header_center_edit);
		centerEdit.setVisibility(View.GONE);
		ImageView leftImage = (ImageView) findViewById(R.id.content_header_left_img);
		leftImage.setImageResource(R.drawable.guanbi_selector);
		ImageView roghtImage1 = (ImageView) findViewById(R.id.content_header_right_img);
		roghtImage1.setVisibility(View.INVISIBLE);
		TextView centerText = (TextView) findViewById(R.id.content_header_center_text);
		centerText.setText("城市");
		TextView rightText = (TextView) findViewById(R.id.content_header_right_text);
		rightText.setVisibility(View.INVISIBLE);
		TextView cityChosed = (TextView) findViewById(R.id.content_header_center_text2);
		cityChosed.setVisibility(View.GONE);
		
		viewPager = (ViewPager) findViewById(R.id.city_choose_viewpager);
    	tipViewGroup = (LinearLayout) findViewById(R.id.city_choose_viewgroup);
    	city_inv_re = (RelativeLayout) findViewById(R.id.city_inv_re);

    	initTips();
    	pageAdapter = new ImgAdAdapter();
    	viewPager.setAdapter(pageAdapter);
    	viewPager.setOnPageChangeListener(this);
    	
    	ViewTreeObserver ivto = city_inv_re.getViewTreeObserver();  
    	ivto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { 
		    @SuppressWarnings("deprecation")
			@Override   
		    public void onGlobalLayout() { 
		    	city_inv_re.getViewTreeObserver().removeGlobalOnLayoutListener(this); 
		    	final int uth = city_inv_re.getHeight();
				ViewTreeObserver vto = tipViewGroup.getViewTreeObserver();  
				vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { 
					@Override   
					public void onGlobalLayout() { 
						tipViewGroup.getViewTreeObserver().removeGlobalOnLayoutListener(this); 
						if(uth!=0)currentPageCount = 3*((UIUtil.winHight-UIUtil.dip2px(CityActivity.this, 50)-tipViewGroup.getHeight())/uth);
						loadData(null);
					}
				}); 
				loadData(null);
		    }
    	});
	}
	
	private void initTips(){
		tips.clear();
		tipViewGroup.removeAllViewsInLayout();
		gridViews.clear();
		for (int i = 0; i < pageCount; i++) {
			ImageView imageView = new ImageView(this);
			LinearLayout.LayoutParams mlp = new LinearLayout.LayoutParams(UIUtil.dip2px(this, 10), UIUtil.dip2px(this, 10));
			mlp.setMargins(UIUtil.dip2px(this, 10), 0, 0, 0);
			imageView.setLayoutParams(mlp);
			if (i == 0) {
				imageView.setBackgroundResource(R.drawable.bg_circle_sel_10);
			} else {
				imageView.setBackgroundResource(R.drawable.bg_circle_white_10);
			}
			if(pageCount<2)imageView.setVisibility(View.INVISIBLE);
			tips.add(imageView);
			tipViewGroup.addView(imageView);
			
			final GridView gridView = (NoScrollGridView)LayoutInflater.from(this).inflate(R.layout.noscroll_gridview, null);
			ItemAdapter itemAdapter = new ItemAdapter(i*currentPageCount, count>(i+1)*currentPageCount?(i+1)*currentPageCount:count);
			gridView.setAdapter(itemAdapter);
			gridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
			gridView.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
					JSONObject job = (JSONObject)gridView.getItemAtPosition(position);
					if(StringUtil.isEmpty(appContext.cityId)||!appContext.cityId.equals(BaseTools.getFrom("id", job))){
						LingGanFragment.freshPage = true;
						//TanDianFragment.freshPage = true;
						WodeFragment.freshPage = true;
						
						((CityHolder)view.getTag()).tag.setVisibility(View.INVISIBLE);
						appContext.cityId = BaseTools.getFrom("province_city", job);
						appContext.cityName = BaseTools.getFrom("city_name",job);
						appContext.cityCode = BaseTools.getFrom("province_city",job);
						appContext.setProperty("city_id", appContext.cityId);
						appContext.setProperty("city_name", appContext.cityName);
						appContext.setProperty("city_code", appContext.cityCode);
					}
					finish();
				}
			});
			gridViews.add(gridView);
		}
	}

	@Override
	public void loadData(Map<String, String> param) {
		HttpService.getByText(URLs.OPEN_CITY, param, new TextHttpResponseHandler() {
			
			@Override
			public void onSuccess(int arg0, Header[] arg1, String arg2) {
				try {
					JSONObject result = new JSONObject(arg2);
					if(result.getInt("status")==0){
						gridViews.clear();
						tips.clear();
						citys.clear();
						JSONObject data = result.getJSONObject("data");
						JSONArray citysJa = data.getJSONArray("list");
						for (int i = 0; citysJa!=null && i < citysJa.length(); i++) {
							citys.add(citysJa.getJSONObject(i));
						}
					}
					count = citys.size();
					pageCount = (count/currentPageCount)+(count%currentPageCount>0?1:0);
					if(pageCount<1)pageCount=1;
					initTips();
					mHandler.sendEmptyMessage(1);
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			
			@Override
			public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) {
				// TODO Auto-generated method stub
				
			}
		});
	}

	@Override
	public void clearData() {
		
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.content_header_left_lay:
			finish();
			break;
		default:
			break;
		}
	}

	static class CityHolder{
		ImageView imgview,tag;
		TextView name;
	}
	
	private class ItemAdapter extends BaseAdapter{
		private int start,end;
		
		public ItemAdapter(int start, int end){
			this.start = start;
			this.end = end;
		}

		@Override
		public int getCount() {
			return end-start;
		}

		@Override
		public Object getItem(int position) {
			return citys.get(position+start);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			JSONObject city = citys.get(position+start);
			CityHolder holder = null;
			if (convertView == null) {
				holder = new CityHolder();
				convertView = LayoutInflater.from(CityActivity.this).inflate(R.layout.city_change_item, null);
				holder.name = (TextView) convertView.findViewById(R.id.city_change_item_text);
				holder.imgview = (RoundImageView) convertView.findViewById(R.id.city_change_item_img);
				holder.tag = (ImageView) convertView.findViewById(R.id.city_change_item_tag);
				convertView.setTag(holder);
			}else{
				holder = (CityHolder) convertView.getTag();
			}	
			holder.tag.setVisibility(!StringUtil.isEmpty(appContext.cityId)&&appContext.cityId.equals(BaseTools.getFrom("province_city", city))?View.VISIBLE:View.GONE);
			holder.name.setText(BaseTools.getFrom("city_name", city));
			ImageLoader.getInstance().displayImage(BaseTools.getFrom( "image.image_url",city), holder.imgview,UIUtil.getImageLoaderDisplayOptions(R.drawable.default140));
			return convertView;
		}
		
	}
	
	private class ImgAdAdapter extends PagerAdapter {
		
		public ImgAdAdapter() {
			super();
		}
		
		@Override
		public int getItemPosition(Object object) {
			return POSITION_NONE;
		}

		@Override
		public int getCount() {
			return pageCount;
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}

		@Override
		public void destroyItem(View container, int position, Object object) {
			((ViewPager) container).removeView(gridViews.get(position));
		}

		/**
		 * 载入图片进去，用当前的position 除以 图片数组长度取余数是关键
		 */
		@Override
		public Object instantiateItem(View container, final int position) {
			((ViewPager) container).addView(gridViews.get(position));
			return gridViews.get(position);
		}
	}
	@Override
	public void onPageScrollStateChanged(int arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onPageSelected(int position) {
		for (int i = 0; i < tips.size(); i++) {
			if(i==position){
				tips.get(i).setBackgroundResource(R.drawable.bg_circle_sel_10);
			} else {
				tips.get(i).setBackgroundResource(R.drawable.bg_circle_white_10);
			}
		}
	}
}
